/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net;

import commands.CommandFactory;
import commands.GameCommand;
import java.util.concurrent.LinkedBlockingQueue;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import scheduler.ISchedulable;

/**
 *
 * @author SafarTimuro
 */
public class GameConnection implements ISchedulable {
    LinkedBlockingQueue<GameCommand> input;
    CommandFactory cf = new CommandFactory();
    Socket conn;
    PrintWriter out;
    BufferedReader in;
    AtomicBoolean open;
    ConnPoll ir;
    
    public GameConnection(Socket conn){
        this.open = new AtomicBoolean(false);
        this.conn = conn;
        ir = new ConnPoll();
        try {
            out = new PrintWriter(
                    new OutputStreamWriter(conn.getOutputStream()));
            in = new BufferedReader(
                    new InputStreamReader(
                      new BufferedInputStream(conn.getInputStream())));
            open.set(true);
            ir.start();
        } catch (IOException ex) {
            Logger.getLogger(GameConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public GameCommand getNextAction() {
        return (input.isEmpty() ? null : input.poll());
    }
    
    public void close(){
        try {
            open.set(false);
            out.close();
            in.close();
            conn.close();
            ir.interrupt();
        } catch (IOException ex) {
            Logger.getLogger(GameConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    class ConnPoll extends Thread {

        @Override
        public void run() {
            try {
                //@todo remove this crap test stuff
                while(open.get()){
                    String line = in.readLine();
                    if(line.equals("quit")) {
                        close();
                        in.readLine();
                        out.write("goodbye");
                        out.flush();
                    }
                    out.write(line);
                    out.flush();
                }
                //@todo parse line into command
                //@todo put command into queue
            } catch (IOException ex) {
                Logger.getLogger(GameConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
